_ = require 'underscore'
###*
 * [convertFieldConditions description]
 * 从json数据中筛选numPerPage，以及其dataList中的yyb
 * {
      "numPerPage": true,
      "dataList": {
        "yyb": true
      }
    }
 * @param  {[type]} fields [description]
 * @return {[type]}        [description]
###
convertFieldConditions = (fields) ->
  conditions = {}
  _.each fields.split(','), (field) ->
    subFields = field.trim()?.split '.'
    lastField = subFields.pop()
    tmpConditions = conditions
    _.each subFields, (field) ->
      if !tmpConditions[field]
        tmpConditions[field] = {}
      tmpConditions = tmpConditions[field]
      return
    if lastField
      tmpConditions[lastField] = true
    return
  return conditions
###*
 * [pickData description]
 * @param  {[type]} originalData [原始数据]
 * @param  {[type]} fields       [字段名]
 * @return {[type]}              [description]
###
pickData = (originalData, fields) ->
  conditions = convertFieldConditions fields
  pick = (src, dst, tmpConditions) ->
    # 如果源数据为数组，对数组的每个项进行tmpConditions的筛选
    if _.isArray src
      _.each src, (tmp) ->
        dst.push pick tmp, {}, tmpConditions
        return
    else
      _.each tmpConditions, (v, k) ->
        # 如果
        if _.isObject v
          if _.isArray src[k]
            dst[k] = []
          else
            dst[k] = {}
          pick src[k], dst[k], v
        else
          dst[k] = src[k]
        return
    return dst
  result = pick originalData, {}, conditions
  return JSON.stringify result


wrapResEnd = (res, fields) ->
  end = res.end
  (data, enconding) ->
    res.end = end
    if !Buffer.isBuffer data
      try
        json = JSON.parse data
      catch e
        json = null
      if json
        data = pickData json, fields
        data = new Buffer data
        res.header 'Content-Length', data.length
        res.end data
    else
      res.end data, enconding
    return
    
###*
 * [field_picker_middleware 根据请求的_fields来pick数据，如?_fields=numPerPage,dataList.id]
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [description]
###
exports.field_picker_middleware = (req, res, next) ->
  fields = req.query?['_fields']
  if fields
    res.end = wrapResEnd res, fields
    next()
  else
    next()